//
//  WCBFormatTextField.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/14.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBFormatTextField.h"

@interface WCBFormatTextField()<UITextFieldDelegate>

@end

@implementation WCBFormatTextField
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
    }
    return self;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField text];
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
        return NO;
    }
    
    text = [text stringByReplacingCharactersInRange:range withString:string];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    // 如果是电话号码格式化，需要添加这三行代码
    //    NSMutableString *temString = [NSMutableString stringWithString:text];
    //    [temString insertString:@" " atIndex:0];
    //    text = temString;
    
    NSString *newString = @"";
    while (text.length > 0) {
        NSString *subString = [text substringToIndex:MIN(text.length, 4)];
        newString = [newString stringByAppendingString:subString];
        if (subString.length == 4) {
            newString = [newString stringByAppendingString:@" "];
        }
        text = [text substringFromIndex:MIN(text.length, 4)];
    }
    
    newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
    
    if (newString.length >= 15) {
        return NO;
    }
    
    [textField setText:newString];
    return NO;
}


#pragma mark - Public
- (NSString *)m_text {
    return [self.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}
@end
